package com.uplooking.service.impl;

import java.sql.Timestamp;
import java.util.UUID;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.uplooking.constant.CustConstants;
import com.uplooking.constant.RedisConstants;
import com.uplooking.dao.GoodDO;
import com.uplooking.dao.OrderDO;
import com.uplooking.pojo.GoodVO;
import com.uplooking.pojo.OrderVO;
import com.uplooking.service.OrderService;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDO orderDO;
	
	@Autowired
	private GoodDO goodDO;
	
	@Autowired
	private StringRedisTemplate redis;
	
	@Override
	@Scheduled(cron="0 * * * * ?")
	public void delOrder() throws Exception {
		System.out.println("计划任务 清除过期未支付订单");
		//遍历所有的缓存订单
		String pattern = RedisConstants.PrefixOrder+"*";
		for(String key:redis.keys(pattern)) {
			for(String text:redis.opsForList().range(key, 0, -1)) {
				OrderVO orderVO = JSONObject.parseObject(text, OrderVO.class);
				if(CustConstants.BuyOrderStatus == orderVO.getOstatus() && 
						new Timestamp(orderVO.getOtime().getTime()+CustConstants.OrderExpire).before(new Timestamp(System.currentTimeMillis()))) {
					//分布式锁
					String lock = RedisConstants.PrefixLock+orderVO.getGno();
					String value = UUID.randomUUID().toString();
					
					//订单移除
					redis.opsForList().remove(key, 1, text);
					
					//库存数量恢复
					String str = RedisConstants.PrefixGood + orderVO.getGno();
					GoodVO goodVO = JSONObject.parseObject(redis.opsForValue().get(str), GoodVO.class);
					goodVO.setGleft(goodVO.getGleft()+orderVO.getGcount());
					redis.opsForValue().set(str, JSONObject.toJSONString(goodVO));
					
					System.out.println("订单:"+orderVO+"过期撤销");
					
					//释放锁
					if(value.equals(redis.opsForValue().get(lock))) {
						redis.delete(lock);
					}
				}
			}
		}

	}

	@Override
	@RabbitListener(queues="mqmymall")
	public void dealOrder(String msg) throws Exception {
		//处理消息队列
		OrderVO orderVO = JSONObject.parseObject(msg, OrderVO.class);
		//下单状态
		orderVO.setOstatus(CustConstants.DownOrderStatus);
		//注意 更新商品表的库存数量
		GoodVO goodVO = goodDO.findById(orderVO.getGno()).orElse(null);
		goodVO.setGleft(goodVO.getGleft()-orderVO.getGcount());
		orderDO.save(orderVO);
		goodDO.save(goodVO);

		System.out.println("订单:"+orderVO+"完成处理");
	}

}
